/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.server.mqtt;


import cn.hutool.core.io.BufferUtil;
import cn.hutool.json.JSONObject;

import com.cetccloud.cimp.adapter.protocol.chain.DefaultDataChain;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author
 * @apiNote 发布订阅服务
 * @Date 2022/7/11  16:44
 **/
@RequiredArgsConstructor
public class MqttServerCallback implements MqttCallbackExtended {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    DefaultDataChain dataChain;
    public MqttServerCallback(DefaultDataChain dataChain) {
        this.dataChain = dataChain;
    }

    /**
     * 建立订阅连接
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        logger.info("connectComplete：{}", serverURI);
    }

    /**
     * 连接中断
     */
    @Override
    public void connectionLost(Throwable cause) {
        // do nothing, just record, this cause has been processed by AutomaticReconnect option.
        logger.warn("connectionLost：{}", cause.toString());
    }

    /**
     * 接收订阅信息
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        JSONObject jsonObject = null;
        try {
            jsonObject = OBJECT_MAPPER.readValue(message.getPayload(), JSONObject.class);
        } catch (IOException e) {
            logger.error("json error：{}", e.getMessage());
        }
        logger.info("收到的数据 : {}", jsonObject);
        if (jsonObject != null) {
            try {

                //TODO 处理数据,接入处理链
            	dataChain.getAuthHandler().fromDtu(
                        BufferUtil.create(message.getPayload()),
                        topic.split("\\/")[topic.split("\\/").length-1]);
//                dataChain.getProtocolEndpoint().fromDtu(
//                        BufferUtil.create(message.getPayload()),
//                        topic.split("\\/")[topic.split("\\/").length-1]);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("update data error: {}", e);
            }
        }
    }

    /**
     * 发送完成
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        logger.info("deliveryComplete---------{}" , token.isComplete());
    }

}
